package com.njiandan.laosijivideo;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import com.google.zxing.Result;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

public class BarcodeScannerActivity extends Activity implements ZXingScannerView.ResultHandler {
    public static final int REQUEST_TAKE_PHOTO_CAMERA_PERMISSION = 200;

    private ZXingScannerView mScannerView;

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);

        mScannerView = new ZXingScannerView(this);
        setContentView(mScannerView);
    }

    @Override
    public void onResume() {
        super.onResume();
        mScannerView.setResultHandler(this);
        if (!requestCameraAccessIfNecessary()) {
            mScannerView.startCamera();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();
    }

    @Override
    public void handleResult(Result result) {
        Intent intent = new Intent();
        intent.putExtra("SCAN_RESULT", result.toString());
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    public void finishWithError(String err) {
        Intent intent = new Intent();
        intent.putExtra("ERROR_CODE", err);
        setResult(Activity.RESULT_CANCELED, intent);
        finish();
    }

    public boolean requestCameraAccessIfNecessary() {
        String[] array = new String[]{Manifest.permission.CAMERA};

        if (ContextCompat
                .checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, array,
                    REQUEST_TAKE_PHOTO_CAMERA_PERMISSION);

            return true;
        }

        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_TAKE_PHOTO_CAMERA_PERMISSION: {
                if (PermissionUtil.verifyPermissions(grantResults)) {
                    mScannerView.startCamera();
                } else {
                    finishWithError("PERMISSION_NOT_GRANTED");
                }
            }
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

class PermissionUtil {
    public static boolean verifyPermissions(int[] grantResults) {
        if (grantResults.length < 1) {
            return false;
        }

        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }

        return true;
    }
}
